import {
    Viewer as CesiumViewer,
    ImageryLayer,
    Ion,
    SceneMode,
    UrlTemplateImageryProvider,
    createWorldTerrainAsync,
} from 'cesium';
import { FC, ReactNode, memo, useMemo, useRef } from 'react';
import { CesiumComponentRef, Viewer } from 'resium';
import { useAppSelector } from '../../store';
import styles from './index.module.scss';
import InitCesium from './InitCesium';

const defaultAccessToken =
    'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIyMjJjYTkwNi1hNzQxLTQxZTktODQzNC1mNGY2MTlkMmMwYjciLCJpZCI6MTI2NDcxLCJpYXQiOjE2Nzc0OTA3ODh9.GhY_tx9JloIaaUpEtg8d_aXjYJ7Qzmb_b0K4CZnjv40';

interface Props {
    children?: ReactNode;
}

const Scene: FC<Props> = (props) => {
    const { children } = props;
    const viewerRef = useRef<CesiumComponentRef<CesiumViewer>>(null);
    const cesium3D = useAppSelector((state) => state.scene.cesium3D);

    const baseLayer = useMemo(() => {
        return new ImageryLayer(
            new UrlTemplateImageryProvider({
                url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}',
            })
        );
    }, []);

    const sceneMode = useMemo(() => {
        return cesium3D ? SceneMode.SCENE3D : SceneMode.SCENE2D;
    }, [cesium3D]);

    const terrain = useMemo(() => {
        // CesiumTerrainProvider.fromUrl()
        Ion.defaultAccessToken = defaultAccessToken;
        return createWorldTerrainAsync();
    }, []);

    return (
        <div
            style={{
                position: 'relative',
                width: '100%',
                height: '100%',
            }}
        >
            <Viewer
                className={styles['root']}
                style={{ zIndex: 0, overflow: 'hidden' }}
                full
                ref={viewerRef}
                shouldAnimate={true}
                baseLayerPicker={false}
                requestRenderMode={true}
                timeline={false}
                animation={false}
                vrButton={false}
                homeButton={false}
                navigationHelpButton={false}
                geocoder={false}
                sceneModePicker={false}
                fullscreenButton={false}
                creditContainer={undefined}
                infoBox={false}
                selectionIndicator={false}
                targetFrameRate={60}
                baseLayer={baseLayer}
                terrainProvider={terrain}
                sceneMode={sceneMode}
            >
                <InitCesium />
                {children}
            </Viewer>
        </div>
    );
};

export default memo(Scene);
